﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Globalization;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Cybozu.SharePoint.AdvancedSearchSB.AdvancedSearchWebPart
{
    [ToolboxItemAttribute(false)]
    public class AdvancedSearchWebPart : WebPart
    {
        protected override void CreateChildControls()
        {
            SPWeb web = SPContext.Current.Web;
            SPRegionalSettings rs = (web.CurrentUser.RegionalSettings != null) ? web.CurrentUser.RegionalSettings : web.RegionalSettings;
            DateTime utcNow = DateTime.UtcNow;
            DateTime datetimeUtc = new DateTime(utcNow.Year, utcNow.Month, utcNow.Day, utcNow.Hour, utcNow.Minute, 0, DateTimeKind.Utc);
            DateTime datetimeLocal = rs.TimeZone.UTCToLocalTime(datetimeUtc);
            int timezoneOffset = (int)datetimeUtc.Subtract(datetimeLocal).TotalMinutes;
            CultureInfo ci = CultureInfo.GetCultureInfo((int)rs.LocaleId);
            
            SPList splist = web.Lists[SPContext.Current.ListId];
            ListDictionary currencyList = new ListDictionary();
            foreach (SPField field in splist.Fields)
            {
                int currencyLCID;
                if (field.Type == SPFieldType.Currency)
                {
                    currencyLCID = (field as SPFieldCurrency).CurrencyLocaleId;
                }
                else if (field.Type == SPFieldType.Calculated && (field as SPFieldCalculated).OutputType == SPFieldType.Currency)
                {
                    currencyLCID = (field as SPFieldCalculated).CurrencyLocaleId;
                }
                else
                {
                    continue;
                }
                if (!currencyList.Contains(currencyLCID))
                {
                    currencyList[currencyLCID] = CultureInfo.GetCultureInfo(currencyLCID).NumberFormat;
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("// <![CDATA[");
            sb.AppendLine("var asRegion = {");
            sb.AppendFormat("    timezoneOffset: {0},\n", timezoneOffset);
            sb.AppendFormat("    dateFormat: \"{0}\",\n", ci.DateTimeFormat.ShortDatePattern);
            sb.AppendFormat("    timeFormat: \"{0}\",\n", ci.DateTimeFormat.ShortTimePattern);
            sb.AppendFormat("    time24: {0},\n", (rs.Time24 ? "true" : "false"));
            sb.AppendFormat("    decimalSeparator: \"{0}\",\n", rs.DecimalSeparator);
            sb.AppendFormat("    thousandSeparator: \"{0}\"\n", rs.ThousandSeparator);
            sb.AppendLine("};");
            sb.AppendLine();

            sb.AppendLine("var asCurrency = {};");
            foreach (DictionaryEntry entry in currencyList)
            {
                NumberFormatInfo nf = entry.Value as NumberFormatInfo;
                sb.AppendFormat("asCurrency[{0}] = {{ ", entry.Key);
                sb.AppendFormat("symbol: \"{0}\", positivePattern: {1}, negativePattern: {2} }};\n", nf.CurrencySymbol, nf.CurrencyPositivePattern, nf.CurrencyNegativePattern);
            }
            sb.AppendLine();

            sb.AppendLine("var asResources = {");
            AppendResource(sb, "AddFilter", Resources.AdvancedSearch.AddFilter);
            AppendResource(sb, "AndCase", Resources.AdvancedSearch.AndCase);
            AppendResource(sb, "BeginsWith", Resources.AdvancedSearch.BeginsWith);
            AppendResource(sb, "Cancel", Resources.AdvancedSearch.Cancel);
            AppendResource(sb, "Contains", Resources.AdvancedSearch.Contains);
            AppendResource(sb, "ContainsUser", Resources.AdvancedSearch.ContainsUser);
            AppendResource(sb, "Filter", Resources.AdvancedSearch.Filter);
            AppendResource(sb, "First", Resources.AdvancedSearch.First);
            AppendResource(sb, "FirstItems", Resources.AdvancedSearch.FirstItems);
            AppendResource(sb, "IsEarlierThan", Resources.AdvancedSearch.IsEarlierThan);
            AppendResource(sb, "IsEarlierThanOrEqualTo", Resources.AdvancedSearch.IsEarlierThanOrEqualTo);
            AppendResource(sb, "IsEqualTo", Resources.AdvancedSearch.IsEqualTo);
            AppendResource(sb, "IsGreaterThan", Resources.AdvancedSearch.IsGreaterThan);
            AppendResource(sb, "IsGreaterThanOrEqualTo", Resources.AdvancedSearch.IsGreaterThanOrEqualTo);
            AppendResource(sb, "IsLaterThan", Resources.AdvancedSearch.IsLaterThan);
            AppendResource(sb, "IsLaterThanOrEqualTo", Resources.AdvancedSearch.IsLaterThanOrEqualTo);
            AppendResource(sb, "IsLessThan", Resources.AdvancedSearch.IsLessThan);
            AppendResource(sb, "IsLessThanOrEqualTo", Resources.AdvancedSearch.IsLessThanOrEqualTo);
            AppendResource(sb, "IsNo", Resources.AdvancedSearch.IsNo);
            AppendResource(sb, "IsNotEqualTo", Resources.AdvancedSearch.IsNotEqualTo);
            AppendResource(sb, "IsNotSameTimeTo", Resources.AdvancedSearch.IsNotSameTimeTo);
            AppendResource(sb, "IsSameTimeTo", Resources.AdvancedSearch.IsSameTimeTo);
            AppendResource(sb, "IsYes", Resources.AdvancedSearch.IsYes);
            AppendResource(sb, "Next", Resources.AdvancedSearch.Next);
            AppendResource(sb, "NextItems", Resources.AdvancedSearch.NextItems);
            AppendResource(sb, "NotContainsUser", Resources.AdvancedSearch.NotContainsUser);
            AppendResource(sb, "NumberOfItemsToDisplay", Resources.AdvancedSearch.NumberOfItemsToDisplay);
            AppendResource(sb, "OK", Resources.AdvancedSearch.OK);
            AppendResource(sb, "OptionNone", Resources.AdvancedSearch.OptionNone);
            AppendResource(sb, "OrCase", Resources.AdvancedSearch.OrCase);
            AppendResource(sb, "Prev", Resources.AdvancedSearch.Prev);
            AppendResource(sb, "PrevItems", Resources.AdvancedSearch.PrevItems);
            AppendResource(sb, "Reset", Resources.AdvancedSearch.Reset);
            AppendResource(sb, "SearchResult", Resources.AdvancedSearch.SearchResult, true);
            sb.AppendLine("};");
            sb.AppendLine("// ]]>");
            sb.AppendLine("</script>");
            this.Controls.Add(new LiteralControl(sb.ToString()));
        }

        protected void AppendResource(StringBuilder sb, string key, string value)
        {
            sb.AppendFormat("    {0}: \"{1}\",\n", key, value);
        }

        protected void AppendResource(StringBuilder sb, string key, string value, bool last)
        {
            if (last)
            {
                sb.AppendFormat("    {0}: \"{1}\"\n", key, value);
            }
            else
            {
                sb.AppendFormat("    {0}: \"{1}\",\n", key, value);
            }
        }
    }
}
